package ro.thich.alchemy;

import android.content.*;
import android.database.*;
import android.database.sqlite.*;
import java.util.*;

public class ElementDAO
{
	private SQLiteDatabase db;
	private ElementSQLiteHelper dbHelper;

	public ElementDAO(Context context) {
		dbHelper = new ElementSQLiteHelper(context);
		db = dbHelper.getWritableDatabase();
	}

	// Close the db
	public void close() {
		db.close();
	}

	/**
	 * Create new TODO object
	 * @param todoText
	 */
	public void createTodo(String todoText) {
		ContentValues contentValues = new ContentValues();
		contentValues.put("element", todoText);
		// Insert into DB
		db.insert("elements", null, contentValues);
	}

	/**
	 * Delete TODO object
	 * @param todoId
	 */
	public void deleteTodo(int elementId) {
		// Delete from DB where id match
		db.delete("elements", "_id = " + elementId, null);
	}

	/**
	 * Get all TODOs.
	 * @return
	 */
	public List getTodos() {
		List elementList = new ArrayList();

		// Name of the columns we want to select
		String[] tableColumns = new String[] {"_id","element"};

		// Query the database
		Cursor cursor = db.query("elements", tableColumns, null, null, null, null, null);
		cursor.moveToFirst();

		// Iterate the results
		while (!cursor.isAfterLast()) {
			Element todo = new Element();
			// Take values from the DB
			todo.setId(cursor.getInt(0));
			todo.setText(cursor.getString(1));

			// Add to the DB
			elementList.add(todo);

			// Move to the next result
			cursor.moveToNext();
		}

		return elementList;
	}
}
